﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoreData;
using ActionServices;
using Helper;
using System.IO;
using System.Threading;

namespace ZidoniCMS.Areas.Administrator.Controllers
{
    public class EmailListManagementController : BaseController
    {
        public EmailListManagementController(IEmailListActionService _emaillist, EmailTemplateActionService _emailtemplate)
            : base(_emaillist, _emailtemplate)
        {
            try
            {
                if (Permission == null || Permission.Count <= 0)
                {
                    SetPermission(UserID, GroupID, UserName);
                }
                SessionManagement.SetSesionValue("pvalue", Permission.FirstOrDefault(c => c.Module.Equals(Helper.ValueDefine.EMAILLIST)).Role);
            }
            catch { }
        }
        static Thread _SendMail;
        //
        // GET: /Administrator/EmailList/
        #region Main
        public ActionResult Index()
        {
            return SetUpSecurity();
        }

        public ActionResult _ShowAll()
        {
            var data = EmailListService.GetList();
            return PartialView(data);
        }
        #endregion
        #region CRUD
        public ActionResult AddOrUpdate(int id = 0)
        {
            return CanUpdate((int)id);
        }

        public ActionResult _AddOrUpdate(int id)
        {
            var data = EmailListService.GetByID(id);
            return PartialView(data);
        }

        /// <summary>
        /// Action
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddOrUpdate(EmailList model)
        {
            var exist = this.EmailListService.GetOneByLINQ(c => c.Email.Equals(model.Email));
            if (exist != null && model.ID == 0)
            {
                return Content("exist");
            }
            if (ValidateData.CheckEmail(model.Email) == false) {
                return Content("wrong");
            }
            var id = this.EmailListService.Save(model);
            var data = this.EmailListService.GetByID(id);
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Delete(int id)
        {
            this.EmailListService.Delete(this.EmailListService.GetByID(id));
            return RedirectToAction("Index", "EmailListManagement");
        }
        #endregion
        #region Other
        static string[] _file = null;
        [HttpPost]
        public ContentResult UploadFiles()
        {
            int i = 0;
            var r = new List<ViewDataUploadFilesResult>();
            if (Request.Files != null && Request.Files.Count != 0)
            {
                if (_file == null)
                    _file = new string[Request.Files.Count];
            }
            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                    continue;
                string savedFileName = Path.Combine(Server.MapPath("~/Media/EmailAttachFolder/"), Path.GetFileName(hpf.FileName));
                hpf.SaveAs(savedFileName);
                _file[i++] = savedFileName;
                r.Add(new ViewDataUploadFilesResult()
                {
                    Name = hpf.FileName,
                    Length = hpf.ContentLength,
                    Type = hpf.ContentType
                });
            }

            return Content("{\"name\":\"" + "Đã đính kèm" + "\"}", "application/json");
        }
        /// <summary>
        /// Get Template by ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetEmailTemplateBody(int id) {
            var data = EmailTemplateService.GetByID(id);
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Send Mail View
        /// </summary>
        /// <returns></returns>
        public ActionResult SendMail() {
            SendMail sd = new SendMail();
            sd.ListTemplateExt = new List<SelectListItem>();
            var Template = EmailTemplateService.GetList();
            SelectListItem sl = new SelectListItem();
            sl.Text = "------------";
            sl.Value = "0";
            sl.Selected = true;
            sd.ListTemplateExt.Add(sl);
            foreach (var item in Template) {
                sl = new SelectListItem();
                sl.Text = item.Name;
                sl.Value = item.ID.ToString();
                sd.ListTemplateExt.Add(sl);
            }
            return View(sd);
        }

        /// <summary>
        /// Send email Action
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SendMail(SendMail model)
        {
            try
            {
                int i = 0;
                if (model.subject == null)
                {
                    model.subject = "Vana Shop";
                }
                if (_file != null)
                {
                    model.file = _file;
                }
                if (model.emailto == null)
                {
                    var mail = EmailListService.GetList();
                    if (mail == null || mail.Count == 0)
                    {
                        return Content("Error/Không có email nào!");
                    }
                    else
                    {
                        model.emailist = new string[mail.Count];
                        foreach (var m in mail.ToList())
                        {
                            model.emailist[i++] = m.Email;
                        }
                    }
                }
                else
                {
                    model.emailist = new string[1];
                    model.emailist[0] = model.emailto;
                }
                if (_SendMail != null)
                {
                    _SendMail = null;
                    _SendMail = new Thread(() => EmailHelper.Send(model.emailist, "trungle.it@gmail.com", "chuacopass", "Zidoni Team", model.subject, model.body, null));
                    _SendMail.Start();
                }
                else
                {
                    _SendMail = new Thread(() => EmailHelper.Send(model.emailist, "trungle.it@gmail.com", "chuacopass", "Zidoni Team", model.subject, model.body, null));
                    _SendMail.Start();
                }
                Thread.Sleep(5000);
                _file = null;
                return Content("Success/Đã gửi bạn có thể đóng form lại !");
            }
            catch
            {
                return Content("Error/Không thể gửi được email");
            }

        }

        #endregion

    }
}
